/**
 * RelationshipBuilder
 * 负责构建实体间的关系网络 (资金往来、通话、同行等)
 */
class RelationshipBuilder {

    /**
     * 构建资金往来关系
     * @param {Object} knex Transaction
     */
    static async buildBankRelationships(knex) {
        const hasTable = await knex.schema.hasTable('bank_transactions');
        if (!hasTable) return;

        // Source -> Target (Money Flow)
        // 核心逻辑：汇总 Source(卡号) 到 Target(对方账号) 的资金
        // TODO: 应该把 '借' 视为 Source->Target, '贷' 视为 Target->Source
        // 目前简化为：每一行记录视为一次 Source -> Target 的交互
        // Warning: 如果数据里有"对方账号"，但没有"对方户名"，也应该记录

        const transfers = await knex('bank_transactions')
            .select(
                'card_number as source',
                'counterparty_name as target_name',
                'counterparty_account as target_account',
                knex.raw('COUNT(*) as count'),
                knex.raw('SUM(ABS(transaction_amount)) as total_amount')
            )
            .whereNotNull('counterparty_account')
            .groupBy('card_number', 'counterparty_account');

        let count = 0;
        for (const t of transfers) {
            await knex('profile_relationships').insert({
                source_identifier: t.source,
                target_name: t.target_name || '未知',
                target_identifier: t.target_account,
                relation_type: 'bank_transfer',
                weight: t.total_amount, // 权重 = 总金额
                details: JSON.stringify({
                    count: t.count,
                    flow: 'out' // 简化假设：这里最好根据借贷标志区分方向，目前的SQL聚合丢失了借贷信息
                })
            });
            count++;
        }

        console.log(`[RelationshipBuilder] Built ${count} bank relationships`);
    }

    /**
     * 构建通话关系
     * @param {Object} knex Transaction
     */
    static async buildCallRelationships(knex) {
        const hasTable = await knex.schema.hasTable('call_records');
        if (!hasTable) return;

        const calls = await knex('call_records')
            .select(
                'phone_number as source',
                'other_number as target',
                knex.raw('COUNT(*) as count'),
                knex.raw('SUM(duration) as total_duration')
            )
            .whereNotNull('other_number')
            .groupBy('phone_number', 'other_number');

        let count = 0;
        for (const c of calls) {
            await knex('profile_relationships').insert({
                source_identifier: c.source,
                target_name: '未知', // 通话记录通常没有对方姓名
                target_identifier: c.target,
                relation_type: 'call',
                weight: c.count, // 权重 = 通话次数
                details: JSON.stringify({
                    duration: c.total_duration
                })
            });
            count++;
        }

        console.log(`[RelationshipBuilder] Built ${count} call relationships`);
    }

    // TODO: 实现同行同住关系 (Travel/Hotel)
    // static async buildCoTravelRelationships(knex) {}
}

module.exports = RelationshipBuilder;
